/**
 * 
 */
package any.desktop;

import java.io.File;
import java.io.Serializable;
import java.net.URI;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Transient;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;

/**
 * @author keke<keke@codehaus.org>
 * @revision $Revision: 70 $
 * @version 0.0.1
 */
@Entity
public class FileItem implements Serializable {
	public static enum Status {
		FAILED, SUCCEED;
	}

	/**
	 * 
	 */
	private static final long	serialVersionUID	= -4967972744957745882L;
	@Id
	@GeneratedValue
	private Long	          id;
	@Column(length = 512, unique = true, nullable = false)
	private URI	              itemURI;
	@Column(nullable = true)
	private Date	          lastIndexed;
	@Column(length = 512, unique = true, nullable = false)
	private String	          md5;
	private Status	          status;
	@Column(length = 64, nullable = false)
	private String	          type;

	public FileItem() {
		super();
	}

	public FileItem(final URI itemURI) {
		super();
		this.itemURI = itemURI;
		md5 = DigestUtils.md5Hex(itemURI.toString());
		type = FilenameUtils.getExtension(itemURI.getPath()).toLowerCase();
	}

	@Override
	public boolean equals(final Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		final FileItem other = (FileItem) obj;
		if (md5 == null) {
			if (other.md5 != null) {
				return false;
			}
		} else if (!md5.equals(other.md5)) {
			return false;
		}
		return true;
	}

	public Long getId() {
		return id;
	}

	public URI getItemURI() {
		return itemURI;
	}

	public Date getLastIndexed() {
		return lastIndexed;
	}

	@Transient
	public Date getLastModified() {
		return new Date(new File(itemURI).lastModified());
	}

	public String getMd5() {
		return md5;
	}

	public Status getStatus() {
		return status;
	}

	public String getType() {
		return type;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (md5 == null ? 0 : md5.hashCode());
		return result;
	}

	@Transient
	public boolean isUpdated() {
		if (getLastIndexed() == null) {
			return true;
		}
		return getLastIndexed().before(getLastModified());
	}

	public void setLastIndexed(final Date lastIndexed) {
		this.lastIndexed = lastIndexed;
	}

	public void setStatus(final Status status) {
		this.status = status;
	}

	@Override
	public String toString() {
		return "FileItem[name=" + itemURI.getSchemeSpecificPart() + "]";
	}

}
